import React, { useEffect, useState } from 'react';

/**
 * Mock 子应用组件
 * 用于文档示例，模拟一个真实的子应用
 */
export const MockSubApp: React.FC<{
  name?: string;
  onMessage?: (data: any) => void;
}> = ({ name = 'mock-app', onMessage }) => {
  const [count, setCount] = useState(0);
  const [message, setMessage] = useState('Hello from Mock Sub App!');
  const [receivedData, setReceivedData] = useState<any>(null);

  useEffect(() => {
    // 监听主应用发来的消息
    const handleMessage = (event: MessageEvent) => {
      if (event.data && event.data.type) {
        setReceivedData(event.data);
        console.log(`[${name}] 收到消息:`, event.data);
      }
    };

    window.addEventListener('message', handleMessage);
    return () => window.removeEventListener('message', handleMessage);
  }, [name]);

  const sendToMain = () => {
    const data = {
      type: 'FROM_SUB_APP',
      message,
      timestamp: new Date().toISOString(),
      count,
      appName: name,
    };

    // 发送消息到主应用
    window.parent.postMessage(data, '*');

    if (onMessage) {
      onMessage(data);
    }

    console.log(`[${name}] 发送消息`, data);
  };

  return (
    <div
      style={{
        fontFamily:
          '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
        margin: 0,
        padding: '24px',
        background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
        color: '#fff',
        height: '100%',
        display: 'flex',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
      }}
    >
      <div
        style={{
          maxWidth: '600px',
          textAlign: 'center',
          background: 'rgba(255, 255, 255, 0.1)',
          backdropFilter: 'blur(10px)',
          borderRadius: '12px',
          padding: '32px',
          boxShadow: '0 8px 32px rgba(0, 0, 0, 0.1)',
          border: '1px solid rgba(255, 255, 255, 0.2)',
        }}
      >
        <h2 style={{ margin: '0 0 16px 0', fontSize: '24px', fontWeight: 600 }}>
          🚀 {name}
        </h2>

        <p style={{ margin: '0 0 24px 0', opacity: 0.9, fontSize: '14px' }}>
          这是一个模拟的子应用示例
        </p>

        {/* 计数器 */}
        <div style={{ marginBottom: '24px' }}>
          <p style={{ margin: '0 0 12px 0', fontSize: '16px' }}>
            计数器: {count}
          </p>
          <button
            onClick={() => setCount(count + 1)}
            style={{
              padding: '8px 16px',
              fontSize: '14px',
              background: 'rgba(255, 255, 255, 0.2)',
              border: '1px solid rgba(255, 255, 255, 0.3)',
              borderRadius: '6px',
              color: '#fff',
              cursor: 'pointer',
              transition: 'all 0.3s',
            }}
            onMouseEnter={(e) => {
              e.currentTarget.style.background = 'rgba(255, 255, 255, 0.3)';
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.background = 'rgba(255, 255, 255, 0.2)';
            }}
          >
            点击增加
          </button>
        </div>

        {/* 消息发送 */}
        <div style={{ marginBottom: '24px' }}>
          <input
            type="text"
            value={message}
            onChange={(e) => setMessage(e.target.value)}
            style={{
              padding: '8px 12px',
              fontSize: '14px',
              borderRadius: '6px',
              border: '1px solid rgba(255, 255, 255, 0.3)',
              background: 'rgba(255, 255, 255, 0.1)',
              color: '#fff',
              width: '200px',
              marginRight: '8px',
            }}
            placeholder="输入消息..."
          />
          <button
            onClick={sendToMain}
            style={{
              padding: '8px 16px',
              fontSize: '14px',
              background: 'rgba(255, 255, 255, 0.2)',
              border: '1px solid rgba(255, 255, 255, 0.3)',
              borderRadius: '6px',
              color: '#fff',
              cursor: 'pointer',
              transition: 'all 0.3s',
            }}
            onMouseEnter={(e) => {
              e.currentTarget.style.background = 'rgba(255, 255, 255, 0.3)';
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.background = 'rgba(255, 255, 255, 0.2)';
            }}
          >
            发送到主应用
          </button>
        </div>

        {/* 接收到的消息 */}
        {receivedData && (
          <div
            style={{
              marginTop: '24px',
              padding: '12px',
              background: 'rgba(255, 255, 255, 0.1)',
              borderRadius: '6px',
              fontSize: '12px',
              textAlign: 'left',
            }}
          >
            <strong>收到来自主应用的消息:</strong>
            <pre
              style={{
                margin: '8px 0 0 0',
                fontSize: '11px',
                whiteSpace: 'pre-wrap',
                wordBreak: 'break-all',
              }}
            >
              {JSON.stringify(receivedData, null, 2)}
            </pre>
          </div>
        )}

        {/* 状态信息 */}
        <div style={{ marginTop: '24px', fontSize: '12px', opacity: 0.7 }}>
          <p style={{ margin: '4px 0' }}>✓ 微应用已加载</p>
          <p style={{ margin: '4px 0' }}>✓ 通信功能正常</p>
          <p style={{ margin: '4px 0' }}>✓ 状态管理正常</p>
        </div>
      </div>
    </div>
  );
};

export default MockSubApp;
